#include "weightthread.h"
#include "UtilityClass.h"
#include <QMessageBox>
#include <QVector>

QVector<QVector<unsigned char>> commands = {
    { 0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xc4, 0x0b},
    { 0x01, 0x03, 0x00, 0x02, 0x00, 0x02, 0x65, 0xcb},
    { 0x01, 0x03, 0x00, 0x04, 0x00, 0x02, 0x85, 0xca},
    { 0x01, 0x03, 0x00, 0x06, 0x00, 0x02, 0x24, 0x0a}};

WEIGHTThread::WEIGHTThread(QObject *parent) : QThread(parent)
{
}

WEIGHTThread::~WEIGHTThread()
{
    if(serialPort->isOpen()) {
        serialPort->close();
    }
    delete serialPort;         // 释放分配的内存
    serialPort = nullptr;      // 将指针设置为 nullptr 以避免悬空指针
}

bool WEIGHTThread::open()
{
    serialPort = new QSerialPort("COM2");
    serialPort->setBaudRate(CBR_19200);
    if (!serialPort->open(QIODevice::ReadWrite)) {
        qDebug()<<" Message ", "the port already at working";
        return false;
    }
    return true;
}

void WEIGHTThread::stop()
{
    isrunning = false;
    if(serialPort->isOpen()) {
        serialPort->close();
    }
}

int WEIGHTThread::sendCommand(QVector<unsigned char> command)
{
    QByteArray commandData(reinterpret_cast<const char*>(command.data()), command.size());
    serialPort->write(commandData);
    if (!serialPort->waitForReadyRead(1000)) { // 等待1秒
        qDebug() << "未能接收到数据：" << serialPort->errorString();
        return 0; // 失败
    }
    // 读取返回数据
    QByteArray responseData = serialPort->readAll();
    // 等待直到所有数据被读取
    while (serialPort->waitForReadyRead(100)) {
        responseData += serialPort->readAll();
    }
    // 检查返回数据长度是否足够
    if (responseData.size() < 7) {
        qDebug() << "返回数据长度不足";
        return 0; // 失败
    }
    // 提取第四到第七个字节并转换为十进制
    int value = (static_cast<unsigned char>(responseData[3]) << 24) |
            (static_cast<unsigned char>(responseData[4]) << 16) |
            (static_cast<unsigned char>(responseData[5]) << 8) |
            (static_cast<unsigned char>(responseData[6]));
    return value;


}

void WEIGHTThread::run()
{
    if(open()) {
        isrunning = true;
        while(isrunning) {
            for(int i = 0; i < 4; i++) {
                int i_w = sendCommand(commands[i]);
                if(i_w > 100) {
                    emit curNum(i+1, getCurrentTime(), i_w);
                }
                Sleep(50);
            }
        }
    }

}
